package com.aaa.controller;

import com.aaa.entity.Menu;
import com.aaa.entity.Role;
import com.aaa.exception.SaveRoleMenuException;
import com.aaa.service.MenuService;
import com.aaa.service.RoleService;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;


    /**
     * 查询所有角色信息
     */
    @RequestMapping("/listAll")
    public PageInfo<Role> listAll(String keyword, Integer currentPage, Integer pageSize){
        PageHelper.startPage(currentPage,pageSize);
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("rname",keyword);
        List<Role> list=roleService.list(queryWrapper);

        PageInfo<Role> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }
    @RequestMapping("/saveOrUpdate")
    public DefaultMsg saveOrUpdate(Role role){
        DefaultMsg defaultMsg=new DefaultMsg();
        boolean b=roleService.saveOrUpdate(role);
        if (!b){
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败");
        }
        return defaultMsg;
    }

    /**
     * 查询所有的菜单信息
     * @return
     */
    @RequestMapping("/listAllMenus")
    public List<Menu> listAllMenus(){
        List<Menu> menus = menuService.listAllMenus();
        return menus;
    }

    /**
     * 保存角色权限信息
     * @return
     */
    @RequestMapping("/savePermits")
    public DefaultMsg savePermits(Integer rid, String mids){
        /*System.out.println(mids);
        Gson gson = new Gson();
        List list = gson.fromJson(mids, List.class);*/


        DefaultMsg defaultMsg;
        try{
            defaultMsg=roleService.savePermits(rid,mids);
        } catch (SaveRoleMenuException e) {
            e.printStackTrace();
            defaultMsg=new DefaultMsg();
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败");
        }


        return defaultMsg;
    }
    /**
     * 查询角色能操作的菜单id(只查询二级菜单)
     * @return
     */
    @RequestMapping("/listMidsByRid")
    public List<Integer> listMidsByRid(Integer rid){
        List<Integer> mids = roleService.listMidsByRid(rid);
        return mids;
    }


    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());
    }

}
